package com.java1234.util;

import com.java1234.entity.Operationlogs;
import com.java1234.service.OperationLogsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
/*
  日志工具类
 */
public class LogUtil {

    @Autowired
    private OperationLogsService operationlogsService;

    public void logOperation(HttpServletRequest request, String operation, String method, String params, String result) {
        Operationlogs log = new Operationlogs();
        log.setUsername(getCurrentUsername());
        log.setOperation(operation);
        log.setMethod(method);
        log.setParams(params);
        log.setResult(result);
        log.setElapsedTime(0L); // 可以计算实际耗时
        log.setCreateTime(new Date());
        log.setIpAddress(request.getRemoteAddr());
        log.setStatus("OK");
        operationlogsService.logOperation(log);
    }

    private String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        } else {
            return principal.toString();
        }
    }
}